package com.zg.nacos.web;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.zg.common.core.R;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.zg.nacos.domain.bo.InstanceInfo;
import com.zg.nacos.domain.req.MicroUserAddReq;
import com.zg.nacos.domain.req.RegisterReq;
import com.zg.nacos.manager.InstanceManager;
import com.zg.nacos.manager.NamingServiceManager;
import com.zg.nacos.service.NacosService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/6/27 11:36
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/micro/nacos")
@Slf4j
@Api(tags = "提供的接口")
public class MicroApiController {

    @Autowired
    private NamingServiceManager namingServiceManager;

    @Autowired
    private InstanceManager instanceManager;

    @Autowired
    private NacosService nacosService;

    @PostMapping("/register")
    @ApiOperation(value = "注册接口")
    public R add(@Validated @RequestBody RegisterReq registerReq) {

//        String namespace = serviceMapping.get(request.getTargetService());
//        if (namespace == null) {
//            return ResponseEntity.badRequest().body("未知的目标服务: " + request.getTargetService());
//        }
        String namespace =registerReq.getNamespace();

        try {
            // 2. 获取对应命名空间的NamingService
            NamingService namingService = namingServiceManager.getNamingService(namespace);

            // 3. 构建服务实例
            Instance instance = new Instance();
            instance.setIp(registerReq.getIp());
            instance.setPort(registerReq.getPort());
            instance.setServiceName(registerReq.getServiceName());

            // 4. 注册到Nacos
            namingService.registerInstance(registerReq.getServiceCode(), instance);

            InstanceInfo info = new InstanceInfo();
            info.setNamespace(namespace);
            info.setServiceName(registerReq.getServiceName());
            info.setServiceCode(registerReq.getServiceCode());
            info.setIp(registerReq.getIp());
            info.setPort(registerReq.getPort());
            info.setHealthCheckUrl(registerReq.getHealthCheckUrl()); // 保存健康检查URL
            instanceManager.addInstance(info);

            return R.success("注册成功! 命名空间: " + namespace);
        } catch (NacosException e) {
            return R.error("注册失败: " + e.getMessage());
        }
    }

}
